package com.ruoyi.system.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.LuntaiTyreInstallLog;
import com.ruoyi.system.domain.LuntaiTyreInstallRequest;
import com.ruoyi.system.domain.LuntaiUser;
import com.ruoyi.system.domain.dto.ClaimsRequestExcel;
import com.ruoyi.system.domain.dto.ClaimsRequestExcel2;
import com.ruoyi.system.domain.dto.LuntaiClaimsRequestDetailDto;
import com.ruoyi.system.domain.dto.LuntaiClaimsRequestDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.LuntaiClaimsRequestMapper;
import com.ruoyi.system.domain.LuntaiClaimsRequest;
import com.ruoyi.system.service.ILuntaiClaimsRequestService;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-13
 */
@Service
public class LuntaiClaimsRequestServiceImpl implements ILuntaiClaimsRequestService {
    @Autowired
    private LuntaiClaimsRequestMapper luntaiClaimsRequestMapper;
    @Value("${url.pc}")
    public String webUrl;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public LuntaiClaimsRequest selectLuntaiClaimsRequestById(Integer id) {
        return luntaiClaimsRequestMapper.selectLuntaiClaimsRequestById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param luntaiClaimsRequest 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<LuntaiClaimsRequest> selectLuntaiClaimsRequestList(LuntaiClaimsRequest luntaiClaimsRequest) {
        return luntaiClaimsRequestMapper.selectLuntaiClaimsRequestList(luntaiClaimsRequest);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param luntaiClaimsRequest 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertLuntaiClaimsRequest(LuntaiClaimsRequest luntaiClaimsRequest) {
        luntaiClaimsRequest.setCreateTime(DateUtils.getNowDate());
        return luntaiClaimsRequestMapper.insertLuntaiClaimsRequest(luntaiClaimsRequest);
    }


    @Override
    public int updateLuntaiClaimsRequest(LuntaiClaimsRequest request) {
        LuntaiClaimsRequest claimRequest = luntaiClaimsRequestMapper.getClaimRequest(request.getId());
        LuntaiUser userInfo = luntaiClaimsRequestMapper.getUserInfo(claimRequest.getUserId());
        if (request.getCode() != null) {
            Integer count = luntaiClaimsRequestMapper.checkCodeEx(request.getCode());
            if (count > 0) {
                throw new UtilException("此轮胎重复了");
            }
        }
        //2 申请状态为 2 或者 3 才修改状态
        if (request.getStatus() != null) {
            SysUser adminInfo = luntaiClaimsRequestMapper.getAdminInfo(SecurityUtils.getUserId());
          List<String> openIds = luntaiClaimsRequestMapper.getAllAdminRoleOpenIds();
            request.setAdminId(Math.toIntExact(adminInfo.getUserId()));
            switch (request.getStatus()) {
                case 2: // 同意
                    // 修改订单状态为成功
                    updateClaimOrder(request.getId(), 1, Math.toIntExact(adminInfo.getUserId()));
                    addAuditLog(request.getId(),1,adminInfo.getUserId(),adminInfo.getPhonenumber());
                    for (String openId : openIds) {
                        sendAuditResult2(1,openId,userInfo.getPhone());
                    }
                    break;
                case 3: // 驳回
                    //修改订单状态为取消
                    updateClaimOrder(request.getId(), 3, Math.toIntExact(adminInfo.getUserId()));
                    addAuditLog(request.getId(),0,adminInfo.getUserId(),adminInfo.getPhonenumber());
                    for (String openId : openIds) {
                        sendAuditResult2(2,openId,userInfo.getPhone());
                    }
                    break;
            }
            if (request.getStatus().equals(2)) {
                //如果是同意的话，就去替换老轮胎
                Integer tyreId = claimRequest.getTyreId();
                LuntaiTyreInstallLog tyre = luntaiClaimsRequestMapper.getTyreById(tyreId);
                LuntaiTyreInstallLog luntaiTyreInstallLog = new LuntaiTyreInstallLog();
                BeanUtils.copyProperties(tyre, luntaiTyreInstallLog);
                luntaiTyreInstallLog.setIsReparation(1);
                luntaiTyreInstallLog.setDot(request.getDotImg());
                luntaiTyreInstallLog.setPatnm(request.getPattenImg());
                luntaiTyreInstallLog.setSpcnm(request.getDriveLicenseImg());
                luntaiTyreInstallLog.setCode(request.getCode());
                luntaiClaimsRequestMapper.replaceTryeByClaims(luntaiTyreInstallLog);
                luntaiClaimsRequestMapper.cancelOldTyre(tyreId);
            }
        }
        return luntaiClaimsRequestMapper.updateLuntaiClaimsRequest(request);
    }
    public void addAuditLog(Integer id,Integer result,Long adminId,String adminPhone){
        luntaiClaimsRequestMapper.addAuditLog(id,1,result,adminId,adminPhone);
    }

    public void updateClaimOrder(Integer claimId, Integer status, Integer adminId) {
        luntaiClaimsRequestMapper.updateClaimOrder(claimId, status, adminId);
    }

    public void sendAuditResult(Integer type, String openId) {
        String passContent = "{\n" +
                "  \"openId\": \"" + openId + "\",\n" +  // 动态赋值
                "  \"result\": \"已通过\",\n" +
                "  \"auditType\": \"门店申请\",\n" +
                "  \"remake\": \"打开小程序查看站内信消息\"\n" +
                "}";

        String refuseContent = "{\n" +
                "  \"openId\": \"" + openId + "\",\n" +  // 动态赋值
                "  \"result\": \"已拒绝\",\n" +
                "  \"auditType\": \"门店申请\",\n" +
                "  \"remake\": \"打开小程序查看拒绝理由\"\n" +
                "}";
        String info = passContent;
        switch (type) {
            case 1:
                info = passContent;
                break;
            case 2:
                info = refuseContent;
                break;
        }
        String url = webUrl + "luntai/sendAuditResult";
        try {
            // 创建 URL 对象
            URL endpoint = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
            // 设置请求方法和头信息
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            // 写入 JSON 数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = info.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("响应码: " + responseCode);
            // 读取响应内容（可选）
            if (responseCode >= 200 && responseCode < 300) {
                System.out.println("请求成功！");
            } else {
                System.out.println("请求失败，响应码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送请求时发生错误，请检查 URL 和网络连接。");
        }
    }

    public void sendAuditResult2(Integer type, String openId,String phone) {
        JSONObject passJson = new JSONObject();
        passJson.put("openId", openId);
        passJson.put("result", "审核通过");
        passJson.put("auditType", "通过");
        passJson.put("remake", "用户" + phone + "申请理赔的已通过");
        String passContent = passJson.toJSONString();
        JSONObject refuseJson = new JSONObject();
        refuseJson.put("openId", openId);
        refuseJson.put("result", "审核驳回");
        refuseJson.put("auditType", "驳回");
        refuseJson.put("remake",phone + "申请理赔的已驳回");
        String refuseContent = refuseJson.toJSONString();
        String info = passContent;
        switch (type) {
            case 1:
                info = passContent;
                break;
            case 2:
                info = refuseContent;
                break;
        }
        String url = webUrl + "luntai/sendAuditResult2";
        try {
            // 创建 URL 对象
            URL endpoint = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
            // 设置请求方法和头信息
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            // 写入 JSON 数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = info.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("响应码: " + responseCode);
            // 读取响应内容（可选）
            if (responseCode >= 200 && responseCode < 300) {
                System.out.println("请求成功！");
            } else {
                System.out.println("请求失败，响应码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送请求时发生错误，请检查 URL 和网络连接。");
        }
    }
    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteLuntaiClaimsRequestByIds(Integer[] ids) {
        return luntaiClaimsRequestMapper.deleteLuntaiClaimsRequestByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteLuntaiClaimsRequestById(Integer id) {
        return luntaiClaimsRequestMapper.deleteLuntaiClaimsRequestById(id);
    }

    @Override
    public List<LuntaiClaimsRequestDto> selectLuntaiClaimsRequestList2(LuntaiClaimsRequestDto requestDto) {
        Long userId = SecurityUtils.getUserId();
        SysUser user = luntaiClaimsRequestMapper.getAdminInfo(userId);
        switch (user.getRemark()) {
            case "管理员":
                break;
            case "门店管理员":
                Integer storeId = luntaiClaimsRequestMapper.getStoreId(Math.toIntExact(userId));
                requestDto.setStoreId(storeId);
                break;
        }
        return luntaiClaimsRequestMapper.selectLuntaiClaimsRequestList2(requestDto);
    }


    @Override
    public LuntaiClaimsRequestDetailDto claimRequestDetail(LuntaiClaimsRequestDto dto) {
        LuntaiClaimsRequestDetailDto detailInfoDto = new LuntaiClaimsRequestDetailDto();
        LuntaiClaimsRequest claimRequest = luntaiClaimsRequestMapper.getClaimRequest(dto.getId());
        detailInfoDto.setRequest(claimRequest);
        LuntaiTyreInstallLog tyre = luntaiClaimsRequestMapper.getTyreById(claimRequest.getTyreId());
        detailInfoDto.setBeforeTyreInfo(tyre);
        LuntaiTyreInstallRequest request = luntaiClaimsRequestMapper.getInstallTyreRequestByTyreId(tyre.getId());
        detailInfoDto.setAfterTyreInfo(luntaiClaimsRequestMapper.getAfterTyreInfo(claimRequest.getCode())); //
        detailInfoDto.setCarInfo(luntaiClaimsRequestMapper.getCarById(request.getCarId()));
        detailInfoDto.setStoreInfo(luntaiClaimsRequestMapper.getStoreByStoreId(request.getStoreId()));
        detailInfoDto.setOrderSn(luntaiClaimsRequestMapper.getOrderSn(dto.getId(), 4));
        detailInfoDto.setTyre(luntaiClaimsRequestMapper.getTyre(request.getTypeBrandId()));
        detailInfoDto.setUserInfo(luntaiClaimsRequestMapper.getUserInfo(request.getUserId()));
        return detailInfoDto;
    }


    private static final int MAX_RETRIES = 3; // 最大重试次数
    private static final int RETRY_DELAY = 2000; // 每次重试间隔（毫秒）

    @Override
    public List<String> getQrcodeInfo(String barcode) {
        String urlStr = "http://221.1.200.234:9008/UMES/Interface/GetTyreInfoByBarcode?barcocde=" + barcode;
        List<String> result = new ArrayList<>();
        int attempt = 0;

        while (attempt < MAX_RETRIES) {
            try {
                // 创建 URL 对象
                URL url = new URL(urlStr);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000); // 连接超时
                conn.setReadTimeout(5000); // 读取超时
                conn.setRequestProperty("Accept", "application/json");

                // 读取响应
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();

                    // 解析 JSON 响应
                    JSONObject jsonResponse = JSON.parseObject(response.toString());
                    if (jsonResponse.getInteger("code") == 200) {
                        JSONObject dataObject = jsonResponse.getJSONObject("data");
                        JSONArray dtArray = dataObject.getJSONArray("dt");
                        if (dtArray != null && !dtArray.isEmpty()) {
                            JSONObject tyreInfo = dtArray.getJSONObject(0);
                            result.add("spcnm: " + tyreInfo.getString("spcnm"));
                            result.add("patnm: " + tyreInfo.getString("patnm"));
                            result.add("dot: " + tyreInfo.getString("dot"));
                            result.add("brnm: " + tyreInfo.getString("brnm"));
                        }
                    }
                    return result; // 请求成功，直接返回结果
                }
            } catch (Exception e) {
                attempt++;
                System.err.println("请求失败（尝试 " + attempt + "/" + MAX_RETRIES + " 次）: " + e.getMessage());

                if (attempt < MAX_RETRIES) {
                    try {
                        Thread.sleep(RETRY_DELAY); // 等待一段时间后重试
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }

        System.err.println("请求失败，已达最大重试次数。");
        return result;
    }

    @Override
    public List<ClaimsRequestExcel> selectLuntaiClaimsRequestList3(LuntaiClaimsRequestDto requestDto) {
        Long userId = SecurityUtils.getUserId();
        SysUser user = luntaiClaimsRequestMapper.getAdminInfo(userId);
        switch (user.getRemark()) {
            case "管理员":
                break;
            case "门店管理员":
                Integer storeId = luntaiClaimsRequestMapper.getStoreId(Math.toIntExact(userId));
                requestDto.setStoreId(storeId);
                break;
        }
        return luntaiClaimsRequestMapper.selectLuntaiClaimsRequestList3(requestDto);
    }

    @Override
    public List<ClaimsRequestExcel2> exportClaimRequestList2() {
        return luntaiClaimsRequestMapper.exportClaimRequestList2();
    }


}
